package com.ruoyi.chat.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.chat.sse.OKHttpStream;
import com.ruoyi.chat.sse.SseClient;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.UUID;

@Component
public class ChatService {
    private static final Logger log = LoggerFactory.getLogger(ChatService.class);

    @Value("${rag_flow.url_prefix}")
    private String prefix;

    private static final String APIKEY = "Bearer ragflow-RjMGI5ZWZjMDQ4YjExZjA4ODQxMDI0Mm";

    @Autowired
    private OKHttpStream okHttpStream;
    @Autowired
    private SseClient sseClient;

    /**
     * post请求ragFlow流式接口
     *
     * @param streamChatUrl 流式接口api地址rag flow
     * @param param 请求参数
     * @return SseEmitter
     */
    public SseEmitter postRagFlow(String streamChatUrl, JSONObject param) {
        String uuid = String.valueOf(UUID.randomUUID());
        // todo 多轮对话 本地优化缓存sse apikey+? 作为sseEmitter的id
        SseEmitter sseEmitter = sseClient.createSse(uuid);
        okHttpStream.chatStream(prefix + streamChatUrl, sseEmitter, param, APIKEY);
        return sseEmitter;
    }

    /**
     * 获取用户缓存信息
     */
    public LoginUser getLoginUser()
    {
        return SecurityUtils.getLoginUser();
    }
}
